import React, { useState, useRef } from "react";
import { Switch } from 'react-vant';
import style from './style.module.scss'
import url1 from '../../../assets/images/image/hdpi/evaluation_star_s.png'
import url2 from '../../../assets/images/icon/common resource/hdpi//circle_icon_drop_down_n.png'
import url3 from '../../../assets/images/image/hdpi/add.png'
import { useRequest } from "ahooks";
import Mydownmenu from "../../../components/mydownmenu";
import { getKnowledgeBase, getKnowledgeBaseListByID } from "../../../api/home";
import { KnowledgeBaseRawState, KnowlegeListItem, fromdata, postpatients, fromdataRawState, postupload } from "../../../api/patientCircle";
import { MyHeader } from "../../../components";
import { DatetimePicker } from 'react-vant';
import { dateFormat } from "../../../utils/formatTime";
import { useNavigate } from "react-router-dom";
import { Notify  } from 'react-vant';
const Index: React.FC = () => {
  const inputRef = useRef<HTMLInputElement | null>(null);
  const navigate=useNavigate()
  // 科室二级菜单开关
  const [administrativeisopen, setAdministrativeisopen] = useState('none')
  // 病症二级菜单开关
  const [diseaseisopen, setDiseaseisopen] = useState('none')
  // DatetimePicker开关
  const [DatetimePickerflag, setDatetimePickerflag] = useState('none')
  // 判断是开始时间还是结束时间
  const [timehintisopen, setTimehintisopen] = useState(false)
  // 悬赏开关
  const [hintisopen, setHintisopen] = useState('block')
  // ------------------------------ 请求-------------------------------
  // 科室请求hooks
  const { data: knowledgeBaseData = [] } = useRequest<
    KnowledgeBaseRawState[],
    []
  >(async () => {
    const resp = await getKnowledgeBase();
    return resp.result;
  });

  // 病症请求hooks
  const { data: diseaseData = [], run } = useRequest(async () => {
    const resp = await getKnowledgeBaseListByID(idRef.current as number);
    return resp.result as KnowlegeListItem[];
  }, {
    manual: true
  });
  // 发布病友圈请求hooks
  // const { data: postpatientsresult = [],run:run1 } = useRequest<
  //   fromdataRawState,
  //   []
  // >(async () => {
  //   const resp = await postpatients(dataRef.current);
  //   console.log(resp);
  //   return resp.result;
  // },{
  //   manual: true
  // });
  
  //----------------------------- 数据 --------------------------------
  const [value, setValue] = React.useState(new Date())
  // 就诊id
  const idRef = useRef<number | null>(null)
  // 写病友圈数据默认值
  const dataRef = useRef<fromdata>({
    title: '',
    departmentId: null,
    disease: '',
    detail: '',
    treatmentHospital: '',
    treatmentStartTime: '',
    treatmentEndTime: '',
    treatmentProcess: '',
    amount: 0
  })
  // 科室
  const [administrative, setAdministrative] = useState('')
  const [HB,setHB]=useState([10,20,30,null])
  const [custom,setCustom]=useState<number|null>(null)
  const [btnactive,setBtnactive]=useState<number|null>(null)
  // 病症
  const [disease, setDisease] = useState('')
  // 开始时间
  const [startTime, setStartTime] = useState('')
  const [overTime, setOverTime] = useState('')
    // 图片列表
  const [imglist,setImgList]=useState<string[]>([])
  // 
  const [filelist,setFileslist]=useState<File[]>([])
  //----------------------------- 事件 --------------------------------
  // 去充值事件
  const handlieTop_up = () => {
    navigate('/wallet/recharge')
  }
  // 发布按钮点击事件
  const handleSubmit = async() => {
    // run1()
    console.log(dataRef.current);
    
    const resp = await postpatients(dataRef.current);
    console.log(resp.result);
    
    Promise.all(filelist.map(item=>postupload(resp.result,item))).then(res=>{
      console.log(res);
      
    })

    navigate(-1)
  }
  // 科室子传父获取参数事件
  const getAdministrative = (item: KnowledgeBaseRawState) => {
    setAdministrativeisopen('none')
    idRef.current = item.id
    setDiseaseisopen('block')
    run()
    dataRef.current.departmentId = item.id
    setAdministrative(item.departmentName)
  }
  // 病症子传父获取参数事件
  const getDisease = (item: KnowlegeListItem) => {
    setDiseaseisopen('none')
    dataRef.current.disease = item.name
    setDisease(item.name)
  }
  // 文件上传事件
  const handleChange=()=>{
    const input = inputRef.current as HTMLInputElement;
    // 2. 获取上传的文件列表
    const files = input.files as FileList;
    setFileslist(Array.from(files))
    if((files.length+imglist.length)>6){
      Notify.show('图片不能超过6张')
        return
    }
    Promise.all(Array.from(files).map(item=>fileToBase64(item))).then(res=>{
        setImgList([...imglist,...res as string[]])
    })
    
    // 文件传base64
    function fileToBase64(file:File) {
      return new Promise((resolve,reject)=>{
        const read = new FileReader()
        read.onload = function () {
            resolve(this.result)
        }
        read.readAsDataURL(file)
      })
    }
    
  }
  return <div>
    <MyHeader></MyHeader>

    <div className={style.write}>
      {/* 标题 */}
      <div className={style.title}>
        <img src={url1} alt="" />
        <input type="text" placeholder="请输入标题(最多20个字)" onChange={(e) => {
          dataRef.current.title = e.target.value

        }} />
      </div>
      {/* 科室 */}
      <div className={style.administrative}>
        <div className={style.administrative_children}>
          <img src={url1} alt="" />
          <div onClick={() => {
            setAdministrativeisopen('block')
          }}>
            <p className={style.text}>{!administrative ? '请选择就诊科室' : administrative}</p>
            <img src={url2} alt="" className={style.arrows} />
          </div>
        </div>
        <div className={style.mack} style={{ display: `${administrativeisopen}` }}>
          <Mydownmenu list={knowledgeBaseData} getval={getAdministrative}></Mydownmenu>
        </div>
      </div>
      {/* 病症 */}
      <div className={style.disease}>
        <div className={style.diseasechildren}>
          <img src={url1} alt="" />
          <div>
            <p className={style.text}>{!disease ? '请选择主要病症' : disease}</p>
            <img src={url2} alt="" className={style.arrows} />
          </div>
        </div>
        <div className={style.mask} style={{ display: `${diseaseisopen}` }}>
          <Mydownmenu list={diseaseData} getval={getDisease}></Mydownmenu>
        </div>
      </div>
      {/* 病症详情 */}
      <div className={style.deteil}>
        <img src={url1} alt="" />
        <div>
          <textarea name="" id="" cols={44} rows={14} placeholder="请输入病症详情" onChange={(e) => {
            dataRef.current.detail = e.target.value
          }}></textarea>
          <p className={style.hints}>不超过300字</p>
        </div>

      </div>
      {/* 治疗经历 */}
      <div className={style.Treatment}>
        <div className={style.Treatment_hander}>
          <p>请输入最近一段治疗经历</p>
        </div>
        <div className={style.Treatment_content}>
          {/* 医院名称 */}
          <div className={style.hospital}>
            <input type="text" placeholder="请输入医院名称" onChange={(e) => {
              dataRef.current.treatmentHospital = e.target.value
            }} />
          </div>
          {/* 开始时间 */}
          <div className={style.startTime} onClick={() => {
            setTimehintisopen(true)
            setDatetimePickerflag('block')
          }}>
            <p className={style.text}>{startTime ? startTime : '请选择开始时间'}</p>
            <img src={url2} alt="" className={style.arrows} />
          </div>
          {/* 结束时间 */}
          <div className={style.overTime} onClick={() => {
            setTimehintisopen(false)
            setDatetimePickerflag('block')

          }}>
            <p className={style.text}>{overTime ? overTime : '请选择结束时间'}</p>
            <img src={url2} alt="" className={style.arrows} />
          </div>
          {/* 治疗过程 */}
          <textarea name="" id="" cols={51} rows={8} placeholder="请输入治疗过程" onChange={(e) => {
            dataRef.current.treatmentProcess = e.target.value
          }}></textarea>
        </div>
      </div>
      {/* 图片上传 */}
      <div className={style.hint}>
        <p>最多可添加6张图片；长按为图片排序</p>
      </div>
      <div className={style.uploadbox}>
        <div className={style.uploadchildren}>
          {
            imglist.length>0&&imglist.map(item=>{
              return <img key={item} src={item} alt="" />
            })
          }
          <input type="file" accept='image/*'  multiple={true} ref={inputRef} style={{display:'none'}} onChange={() => handleChange()}/>
          <img src={url3} alt="" onClick={() => inputRef.current?.click()}/>
        </div>
      </div>
      {/* 悬赏 */}
      <div className={style.hint}>
        <p>提示悬赏额度</p>
        <Switch size="20px" defaultChecked className={style.switch} onChange={(value) => {
          setHintisopen(value?'block':'none')
          dataRef.current.amount=0
        }} />
      </div>
      <div className={style.Reward_amount} style={{ display: `${hintisopen}` }}>
        <p>提升额度可获得更多的关注,得到更多建议</p>
        <div className={style.Radiobtn}>
          {
            HB.map((item,ind)=>{
              if (item) {
                return <button key={ind} 
              className={btnactive===ind?style.active:''}
              onClick={()=>{
                setBtnactive(ind)
                  dataRef.current.amount = item
              }}>{item+'H币'}</button>
              }else{
                return <input type="text" placeholder="自定义H币" 
                className={btnactive===ind?style.active:''}
                key={ind} onChange={(e)=>{
                  setCustom(Number(e.target.value))
                }}
                onClick={()=>{
                  setBtnactive(ind)
                }}
                onKeyDown={(e)=>{
                  if(e.keyCode===13){
                    dataRef.current.amount = custom
                  }
                }}/>
              }
            })
          } 
          <p className={style.top_up}>当前H币余额300.不足？去<span onClick={() => {
            handlieTop_up()
          }}>充值</span></p>
        </div>
      </div>
      <button className={style.submit} onClick={() => {
        handleSubmit()
      }}>发布</button>
    </div>
    <div className={style.DatetimePicker} style={{ display: `${DatetimePickerflag}` }}>
      <DatetimePicker
        title='选择年月日'
        type='date'
        minDate={new Date(2020, 0, 1)}
        maxDate={new Date(2025, 10, 1)}
        value={value}
        onChange={setValue}
        onConfirm={() => {
          setDatetimePickerflag('none')
          if (timehintisopen) {
            const timers = dateFormat(value.getTime(), 'yyyy-MM-dd')
            setStartTime(timers)
            dataRef.current.treatmentStartTime = timers
          } else {
            const timers = dateFormat(value.getTime(), 'yyyy-MM-dd')
            setOverTime(timers)
            dataRef.current.treatmentEndTime = timers
          }
        }
        }
      />
    </div>
  </div>

};

export default Index;
